package network;


import java.io.IOException;
import java.net.*;
import java.util.Scanner;


public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;


    public UdpEchoClient(String ip,int port) throws SocketException {
        serverIp = ip;
        serverPort = port;
        //这个new操作，就不在指定端口
        socket = new DatagramSocket();
    }
    //让这个客户端反复从控制台读取用户输入的请求，把这个内容构造成UDP请求，发送给服务器，再读取服务器返回的UDP响应
    //最终再显示在客户端的屏幕上
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动");
        while (true){
            //从控制台读取用户内容
            System.out.println("->");//命令提示符，提示用户输入字符串
            String request = scanner.next();
            //构造请求对象并发给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            //读取服务器的响应，并解析内容
            DatagramPacket responPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responPacket);
            String response = new String(responPacket.getData(),0,responPacket.getLength());
            System.out.println(response);

        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
